package com.yh.correct.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.yh.common.utils.ExcelUtil;
import com.yh.correct.model.CorrectedPerson;
import com.yh.correct.model.Page;
import com.yh.correct.model.ResultData;
import com.yh.correct.model.StateChange;
import com.yh.correct.service.ICorrectedPersonService;
import com.yh.correct.service.IStateChangeService;

/**
 * 矫正状态变更记录控制层
 * 
 * @author 王鹏程 
 * @date 2017.03.14
 * @time 13:39
 */
@RestController
@RequestMapping("/stateChange")
public class StateChangeController {
	/**
	 * 日志记录
	 */
	private static Logger logger = LogManager.getLogger(StateChangeController.class);
	/**
	 * 注入矫正状态变更记录服务层接口
	 */
	@Autowired
	private IStateChangeService stateChangeService;
	/**
	 * 注入矫正人员接口服务层接口
	 */
	@Autowired
	ICorrectedPersonService ips;
	/**
	 * 矫正状态变更页跳转
	 * 
	 * @param 
	 * @return
	 */
	@RequestMapping(value="/stateSkip")
	public ModelAndView skip(){ 
		return new ModelAndView("end/state");
	}
	/**
	 * 矫正状态变更记录页跳转
	 * 
	 * @param 
	 * @return
	 */
	@RequestMapping(value="/stateChangeSkip")
	public ModelAndView stateChangeSkip(){ 
		return new ModelAndView("end/statechange");
	}
	/**
	 * 模糊查询矫正人员
	 * 
	 * @param name
	 * @param pageSize
	 * @param pageNum
	 * @return
	 */
	@RequestMapping(value="/getLikePerson")
	public ResultData getLikePerson(@RequestParam("cname") String name,String jname,int pageSize , int pageNum){
		Map<String,Object> condition=new HashMap<String,Object>();
		condition.put("pageSize", pageSize);
		condition.put("pageNum", pageNum);
		condition.put("name", name);
		condition.put("jname", jname);
		Page page = stateChangeService.queryLikePersons(condition);
		ResultData rd=new ResultData();
		if(page!=null){
			List<Object> person = new ArrayList<Object>();
			person.add(page);
			rd.setCode(0);
			rd.setMessage("查询成功！");
			rd.setData(person);
		}else{
			rd.setCode(-1);
			rd.setMessage("查询失败！");
		}
		logger.debug("模糊查询矫正人员!");
		return rd;
	}
	/**
	 * 修改矫正状态前查询单条矫正人员信息
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/beforEditState")
	public ModelAndView getPerson(int id){ 
		logger.debug(id);
		CorrectedPerson person = new CorrectedPerson();
		person.setId(id);
		Map<String,Object> map = stateChangeService.getPersonById(person);
		logger.debug("修改矫正状态前查询单条矫正人员信息!");
		return new ModelAndView("end/state_edit",map);
	}
	/**
	 * 修改矫正状态
	 * 
	 * @param correctedPerson
	 * @return
	 */
	@RequestMapping(value="/editState")
	public ResultData editState(CorrectedPerson cPerson,String beforState){
		StateChange change = new StateChange();
		change.setBeforState(beforState);
		change.setPid(cPerson.getId());
		change.setGid(1);
		change.setJid(cPerson.getJid());
		change.setBeforState(beforState);
		change.setAfterState(cPerson.getState());
		change.setChangeDate(new Date());
		logger.debug("单条矫正人员信息!"+beforState);
		logger.debug("单条矫正!"+change);
		
		int c = stateChangeService.editState(cPerson);
		int i = stateChangeService.addStateChange(change);
		ResultData rd=new ResultData();
		if(c>0 && i>0){
			rd.setCode(0);
			rd.setMessage("修改成功！");
		}else{
			rd.setCode(-1);
			rd.setMessage("修改失败！");
		}
		logger.debug("修改矫正状态!");
		return rd;
	}
	/**
	 * 删除矫正状态变更记录
	 * 
	 * @param expire
	 * @return
	 */
	@RequestMapping(value="/del")
	public ResultData delStateChange(StateChange change){ 
		int i = stateChangeService.delStateChange(change);
		ResultData rd=new ResultData();
		if(i>0){
			rd.setCode(0);
			rd.setMessage("删除成功！");
		}else{
			rd.setCode(-1);
			rd.setMessage("删除失败！");
		}
		logger.debug("删除矫正状态变更记录!");
		return rd;
	}
	/**
	 * 模糊查询矫正状态变更记录
	 * 
	 * @param name
	 * @param pageSize
	 * @param pageNum
	 * @return
	 */
	@RequestMapping(value="/getLike")
	public ResultData getLikeStateChanges(@RequestParam("cname") String name,String jname,int pageSize,int pageNum){ 
		Map<String,Object> condition=new HashMap<String,Object>();
		condition.put("pageSize", pageSize);
		condition.put("pageNum", pageNum);
		condition.put("name", name);
		condition.put("jname", jname);
		Page page = stateChangeService.queryLikeStateChanges(condition);
		ResultData rd=new ResultData();
		if(page!=null){
			List<Object> change = new ArrayList<Object>();
			change.add(page);
			rd.setCode(0);
			rd.setMessage("查询成功！");
			rd.setData(change);
		}else{
			rd.setCode(-1);
			rd.setMessage("查询失败！");
		}
		logger.debug("模糊查询矫正状态变更记录!");
		return rd;
	}
	/**
	 * 导出Excle
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/excel")
	public String outExcle(HttpServletRequest request, HttpServletResponse response,@RequestParam("cname") String name,String jname){
		Map<String,Object> condition=new HashMap<String,Object>();
		condition.put("jname", jname);
		condition.put("name", name);
		String fileName = "矫正状态变更记录文件";
		LinkedList<Map<String, Object>> projects = stateChangeService.getAllStateChanges(condition);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sheetName", "sheet1");
		projects.add(0, map);
		String columnNames[] = { "编号", "矫正单位", "姓名", "变更前状态", "变更后状态", "更改人用户名", "变更日期"};
		String keys[] = { "id", "jname", "name", "beforstate", "afterstate", "username", "changedate",};
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			ExcelUtil.createWorkBook(projects, keys, columnNames).write(os);
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] content = os.toByteArray();
		InputStream is = new ByteArrayInputStream(content);
		response.reset();
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		try {
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (final IOException e) {
			try {
				throw e;
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} finally {
			if (bis != null)
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (bos != null)
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		return null;
	}
	
}
